<template>
  <edit-card :title="'创建NoteBook'" :confirm-text="'确定'" :type="'add'" :loading="pageLoading || subLoading" @confirm="submit">
    <a-anchor
      style="position: absolute; top: 16px; right: 16px; width: 112px"
      :items="[
        { key: '1', href: '#components-anchor-demo-basic', title: 'NoteBook详情' },
        { key: '2', href: '#components-anchor-demo-static', title: '资源分配' }
      ]"
      wrapper-class="a-anchor-class"
      :target-offset="500"
      :offset-top="80 + 54"
      @click.prevent
    />
    <div id="components-anchor-demo-basic" class="default-class-title">NoteBook详情</div>
    <a-form
      ref="mainFormRef"
      :colon="false"
      :model="mainForm"
      style="width: 824px"
      :rules="mainFormRules"
      name="mainForm"
      :label-align="'left'"
    >
      <a-form-item label="名称" name="name">
        <g-input v-model:value="mainForm.name" v-trim :search="false" class="w-440" placeholder="请输入名称" :maxlength="200" />
      </a-form-item>
      <a-form-item label="使用时长" name="usageDuration">
        <a-select v-model:value="mainForm.usageDuration" :options="timeOptions" class="w-440" />
      </a-form-item>
      <a-form-item label="镜像" name="imageId">
        <div class="radio-group-box">
          <a-radio-group v-model:value="mainForm.imageId" class="radio-group-content" @change="imageSelect">
            <div
              v-for="item in imageList"
              :key="item.id"
              :for="item.id"
              :class="['radio-group-item', mainForm.imageId === item.id && 'radio-group-item--active']"
            >
              <a-radio :id="item.id" class="w-736" :value="item.id">
                <div class="image-name">{{ item.imageName }}</div>
                <div class="image-info">{{ item.description }}</div>
              </a-radio>
            </div>
          </a-radio-group>
        </div>
      </a-form-item>
      <a-form-item label="框架" name="frame">
        <g-input v-trim :value="mainForm.frame" :search="false" disabled class="w-440" placeholder="" />
      </a-form-item>
      <a-form-item label="描述" name="remark">
        <a-textarea v-model:value="mainForm.remark" v-trim class="w-440 h-106" placeholder="请输入描述" :maxlength="200" show-count />
      </a-form-item>
    </a-form>

    <div id="components-anchor-demo-static" class="default-class-title mt-120">资源分配</div>
    <a-form ref="resourceRef" :model="resourceForm" :colon="false" :rules="resourceRules" name="resourceForm" :label-align="'left'">
      <a-form-item label="GPU" name="gpu">
        <a-select v-model:value="resourceForm.gpu" :options="GPU_OPTIONS" class="w-440" />
      </a-form-item>
      <a-form-item label="CPU" name="cpuMemory">
        <a-select v-model:value="resourceForm.cpuMemory" :options="CPU_OPTIONS" class="w-440" @change="cpuMemoryChange" />
      </a-form-item>
    </a-form>
  </edit-card>
</template>

<script lang="ts" setup>
  import { message, type RadioChangeEvent } from 'ant-design-vue'
  import type { Rule } from 'ant-design-vue/es/form'
  import { SelectValue } from 'ant-design-vue/es/select'
  import { cloneDeep } from 'g6-fn'
  import { ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRouter } from 'vue-router'

  import { algoDevApi, mirrorManageApi } from '@/services/api'
  import { validateBitLen, validateDirName } from '@/utils'

  import { CPU_OPTIONS, GPU_OPTIONS } from '../../options'

  const router = useRouter()

  const timeOptions = [
    { label: '1小时', value: 1 },
    { label: '2小时', value: 2 },
    { label: '4小时', value: 4 },
    { label: '6小时', value: 6 },
    { label: '12小时', value: 12 },
    { label: '24小时', value: 24 }
  ]

  /** NoteBook详情 -------------------------------------------------------------------------------- */
  interface MainForm {
    name: string
    usageDuration: number | undefined
    imageId: number | undefined
    frame: string
    remark: string
  }
  let mainFormRef = ref()
  let mainForm = ref<MainForm>({
    name: '',
    usageDuration: 1,
    imageId: undefined,
    frame: '',
    remark: ''
  })

  const mainFormRules: Record<string, Rule[]> = {
    name: [
      { required: true, trigger: 'change', message: '请输入名称' },
      { validator: validateDirName() },
      { validator: validateBitLen(200), trigger: 'change' }
    ],
    usageDuration: [{ required: true, message: '请选择使用时长' }],
    imageId: [{ required: true, message: '请选择镜像' }],
    frame: [{ required: true }]
  }
  // 获取镜像数据
  const imageList = ref()

  const { loading: pageLoading, runAsync: runGetImageList } = useRequest(mirrorManageApi.imageCommon, {
    onSuccess: (data: any) => {
      console.log('data', data)
      imageList.value = data.data
    }
  })
  runGetImageList({ dockerPurposeType: 1 })

  const imageSelect = (e: RadioChangeEvent) => {
    let val = e.target.value
    mainForm.value.frame = imageList.value.find((item: any) => item.id === val)?.frame
    mainFormRef.value?.validate('frame')
  }

  /* 资源分配逻辑 -------------------------------------------------------------------------- */
  let resourceRef = ref()
  let resourceForm = ref({
    gpu: 0,
    cpuMemory: '1-2',
    cpu: 1,
    memory: 2
  })

  const resourceRules: Record<string, Rule[]> = {
    gpu: [{ required: true, message: '请选择GPU' }],
    cpuMemory: [{ required: true, message: '请选择CPU' }]
  }

  const cpuMemoryChange = (val: string | SelectValue) => {
    if (typeof val === 'string' && val.includes('-')) {
      resourceForm.value.cpu = Number(val.split('-')[0])
      resourceForm.value.memory = Number(val.split('-')[1])
    }
  }

  /* 表单提交 -------------------------------------------------------------------------- */
  const formatParams = () => {
    let mainFormData = cloneDeep(mainForm.value)
    delete mainFormData.frame
    let resourceFormData = cloneDeep(resourceForm.value)
    delete resourceFormData.cpuMemory
    let paramData = { ...mainFormData, ...resourceFormData }
    console.log('提交的数据', paramData)
    return paramData
  }
  const { loading: subLoading, runAsync: addTraining } = useRequest<ResponseData<void>>(algoDevApi.addNotebook)
  const submit = async () => {
    await mainFormRef.value?.validate()
    await resourceRef.value?.validate()
    await addTraining(formatParams(), { isAddUid: true })
    message.success('创建成功')
    router.back()
  }
</script>

<style lang="less" scoped>
  .w-440 {
    width: 440px;
  }

  :deep(.ant-form-item) {
    margin-bottom: 40px;

    .ant-form-item-label > label {
      width: 120px;
    }
  }

  .default-class-title {
    .font20b();

    position: relative;
    margin-bottom: 50px;

    &::before {
      position: absolute;
      top: 50%;
      left: -16px;
      width: 3px;
      height: 22px;
      background: #1868e9;
      border-radius: 0 2px 2px 0;
      content: '';
      transform: translateY(-50%);
      flex: none;
      order: 0;
      align-self: stretch;
      flex-grow: 0;
    }
  }

  .a-anchor-class {
    position: absolute !important;
    top: 54px;
    right: 10;
  }

  .radio-group-box {
    display: flex;
    align-items: flex-start;
    padding: 4px 0;
    width: 760px;
    border: 1px solid #d9dadb;
    border-radius: 6px;
    flex-direction: column;
    gap: 4px;
    align-self: stretch;

    .radio-group-content {
      width: 100%;
    }

    .radio-group-item {
      padding: 8px 16px;

      &:hover {
        background: rgba(17, 103, 240, 0.02);
      }

      &--active {
        background: rgba(17, 103, 240, 0.03);
      }

      .radio {
        width: 100%;
      }

      .image-info {
        padding-left: 8px;
        font-size: 12px;
        color: @text03;
      }

      .image-name {
        padding-left: 8px;
        font-size: 14px;
        color: @text01;
      }
    }
  }
</style>
